//
//  GameLayer.m
//  FrogDrying
//
//  Created by Le Thanh Hai on 4/2/13.
//  Copyright 2013 __MyCompanyName__. All rights reserved.
//

#import "GameLayer.h"
#import "TopLayer.h"
#import "SimpleAudioEngine.h"
#import "EndGameLayer.h"

@implementation GameLayer
+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	GameLayer *layer = [GameLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

-(void)onExit
{
    [super onExit];
    [[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
}

// on "init" you need to initialize your instance
-(id) init
{
	if( (self = [super init]) ) {
        ADD_BACKGROUND
        
        CGSize size = [[CCDirector sharedDirector] winSize];
        self.isTouchEnabled = YES;
        [self scheduleUpdate];
        
        CCSprite *sp1 = [CCSprite spriteWithFile:@"time_bg.png"];
        sp1.anchorPoint = ccp(0, 1);
        [self addChild:sp1];
        sp1.position = ccp(0, size.height - 20);
        
        CCSprite *sp2 = [CCSprite spriteWithFile:@"gameScene_bgnumber.png"];
        sp2.anchorPoint = ccp(1, 1);
        [self addChild:sp2];
        sp2.position = ccp(size.width, size.height - 20);
        
        CCMenuItem *pause = [CCMenuItemImage itemWithNormalImage:@"buttonPause.png" selectedImage:nil block:^(id sender) {
            [[PauseScreen shareScreen] show];
        }];
        CCMenu *menu = [CCMenu menuWithItems:pause, nil];
        [self addChild:menu];
        menu.position = CGPointZero;
        menu.anchorPoint = CGPointZero;
        pause.anchorPoint = ccp(1, 1);
        pause.position = ccp(size.width, size.height - 15);
        
        lotusAnimation = [[SpriteLotus alloc] init];
        lotusAnimation.anchorPoint = CGPointZero;
        lotusAnimation.position = CGPointZero;
        [self addChild:lotusAnimation];
        
        ballon = [[SpriteBalloon alloc] init];
        [self addChild:ballon];
        
        allLotus = [lotusAnimation lotus];
        
        [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"back.caf"];
        allFrogs = [[NSMutableArray alloc] init];
        for (int i = 0; i < [allLotus count]; i++) {
            SpriteFrog *frog = [[SpriteFrog alloc] init];
            frog.position = ccp(30, 85);
            frog.allLotus = allLotus;
            [self addChild:frog];
            [allFrogs addObject:frog];
            [frog setCurrentLotus:[allLotus objectAtIndex:0]];
        }
        
        
        time = 90;
        timeCountDown = [CCLabelBMFont labelWithString:@"90" fntFile:@"number_white.fnt"];
        timeCountDown.anchorPoint = ccp(0, 1);
        timeCountDown.position = ccp(25, size.height - 22);
        [self addChild:timeCountDown z:100];
        
        
        lbScore = [CCLabelBMFont labelWithString:@"0" fntFile:@"number_white.fnt"];
        lbScore.anchorPoint = ccp(1, 1);
        lbScore.position = ccp(size.width - 30, size.height - 22);
        [self addChild:lbScore z:100];
        score = 0;
    }
	return self;
}

-(void)registerWithTouchDispatcher {
	CCDirector *director = [CCDirector sharedDirector];
	[[director touchDispatcher] addTargetedDelegate:self priority:kCCMenuHandlerPriority+1 swallowsTouches:NO];
}

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
	CGPoint location = [touch locationInView:[touch view]];
	location = [[CCDirector sharedDirector] convertToGL:location];
	[self tapDownAt:location];
	return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
	CGPoint location = [touch locationInView:[touch view]];
	location = [[CCDirector sharedDirector] convertToGL:location];
	[self tapMoveAt:location];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
	CGPoint location = [touch locationInView:[touch view]];
	location = [[CCDirector sharedDirector] convertToGL:location];
	[self tapUpAt:location];
}

- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event {
	CGPoint location = [touch locationInView:[touch view]];
	location = [[CCDirector sharedDirector] convertToGL:location];
	[self tapUpAt:location];
}

// touch began
- (void)tapDownAt:(CGPoint)location {
	location = ccpSub(location, self.position);
    dragSprite = nil;
    for (int i = [allFrogs count] - 1; i >= 0 ; i --) {
        SpriteFrog *getSprite = [allFrogs objectAtIndex:i];
        if (CGRectContainsPoint([getSprite rect], location)) {
            lastPosition = dragSprite.position;
            dragSprite = getSprite;
            dragSprite.state = kStateDrag;
            break;
        }
    }
}


// touch move
- (void)tapMoveAt:(CGPoint)location
{
    lastPosition = dragSprite.position;
    dragSprite.position = ccpAdd(ccpAdd(lastPosition, OFFSET_POINT), ccpSub(location, lastPosition));
}

// touch end, cancel
- (void)tapUpAt:(CGPoint)location
{
    BallAnimation *ball = [ballon getBallAtLocation:location];
    if ((ball != nil) && dragSprite) {
        [ball addFrogWith:0];
        dragSprite.state = kStateReset;
        
        // calculater score
        score++;
        lbScore.string = [NSString stringWithFormat:@"%d", score];
    } else {
        dragSprite.state = kStateFall;
    }
}

-(void)update:(ccTime)dt
{
    //[lotus update:dt];
    time -= dt;
    timeCountDown.string = [NSString stringWithFormat:@"%d", (int)time];
    [ballon update:dt];
    if (time <= 0) {
        [[CCDirector sharedDirector] replaceScene:[TopLayer scene]];        
        [Global setScore:score];
        if ([ShareFacebook canUseFacebook]) {
            [[ShareFacebook shareInstance] postScore:score complete:^{
                NSLog(@"submit score successfull");
                [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:0.5 scene:[EndGameLayer scene]]];
            }];
        } else {
            [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:0.5 scene:[EndGameLayer scene]]];
        }
    }
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	[super dealloc];
}
@end
